﻿namespace JxcLite.Services;

[WebApi, Service]
class FinanceService(Context context) : ServiceBase(context), IFinanceService
{
    public Task<PagingResult<AccountInfo>> QueryAccountsAsync(PagingCriteria criteria)
    {
        return Database.Query<JxAccountHead>(criteria).ToPageAsync<AccountInfo>();
    }

    public async Task<AccountInfo> GetDefaultAccountAsync(string type)
    {
        return new AccountInfo
        {
            Type = type,
            AccountNo = await Database.GetMaxAccountNoAsync(type),
            Status = FlowStatus.Save,
            AccountDate = DateTime.Now
        };
    }

    public async Task<Result> DeleteAccountsAsync(List<AccountInfo> infos)
    {
        if (infos == null || infos.Count == 0)
            return Result.Error(Language.SelectOneAtLeast);

        var database = Database;
        var oldFiles = new List<string>();
        var result = await database.TransactionAsync(Language.Delete, async db =>
        {
            foreach (var item in infos)
            {
                await db.DeleteFilesAsync(item.Id, oldFiles);
                await db.DeleteAsync<JxAccountList>(d => d.HeadId == item.Id);
                await db.DeleteAsync<JxAccountHead>(item.Id);
            }
        });
        if (result.IsValid)
            AttachFile.DeleteFiles(oldFiles);
        return result;
    }

    public async Task<Result> SaveAccountAsync(UploadInfo<AccountInfo> info)
    {
        var database = Database;
        var model = await database.QueryByIdAsync<JxAccountHead>(info.Model.Id);
        model ??= new JxAccountHead();
        model.FillModel(info.Model);

        var vr = model.Validate(Context);
        if (!vr.IsValid)
            return vr;

        var fileFiles = info.Files?.GetAttachFiles(nameof(JxAccountHead.Files), "AccountFiles");
        return await database.TransactionAsync(Language.Save, async db =>
        {
            if (model.IsNew)
                model.AccountNo = await db.GetMaxAccountNoAsync(model.Type);
            await db.AddFilesAsync(fileFiles, model.Id, key => model.Files = key);
            await db.SaveAsync(model);
            info.Model.Id = model.Id;
        }, info.Model);
    }
}